/**
 * 小程序性能优化工具类
 * 提供内存监控、性能检测、优化建议等功能
 */

class MiniProgramPerformance {
  constructor() {
    this.monitoringEnabled = true;
    this.performanceData = {
      memoryUsage: [],
      networkLatency: [],
      renderTime: [],
      videoLoadTime: [],
      startTime: Date.now()
    };
    
    this.thresholds = {
      memoryWarning: 0.8,      // 内存使用80%警告
      networkSlow: 3000,       // 网络延迟3秒为慢速
      renderSlow: 1000,        // 渲染时间1秒为慢速
      videoLoadSlow: 5000      // 视频加载5秒为慢速
    };
    
    this.optimizationCallbacks = new Map();
    this.monitoringInterval = null;
    
    console.log('[小程序性能] 性能监控工具初始化');
  }

  /**
   * 启动性能监控
   */
  startMonitoring(options = {}) {
    const {
      interval = 30000,        // 30秒检查一次
      enableMemoryMonitoring = true,
      enableNetworkMonitoring = true,
      enableRenderMonitoring = true
    } = options;

    if (this.monitoringInterval) {
      clearInterval(this.monitoringInterval);
    }

    this.monitoringEnabled = true;
    
    // 定时性能检查
    this.monitoringInterval = setInterval(() => {
      this.performanceCheck();
    }, interval);

    // 内存监控
    if (enableMemoryMonitoring) {
      this.setupMemoryMonitoring();
    }

    // 网络监控
    if (enableNetworkMonitoring) {
      this.setupNetworkMonitoring();
    }

    // 渲染性能监控
    if (enableRenderMonitoring) {
      this.setupRenderMonitoring();
    }

    console.log('[小程序性能] 性能监控已启动');
  }

  /**
   * 停止性能监控
   */
  stopMonitoring() {
    if (this.monitoringInterval) {
      clearInterval(this.monitoringInterval);
      this.monitoringInterval = null;
    }
    
    this.monitoringEnabled = false;
    console.log('[小程序性能] 性能监控已停止');
  }

  /**
   * 设置内存监控
   */
  setupMemoryMonitoring() {
    // 小程序内存警告监听
    if (uni.onMemoryWarning) {
      uni.onMemoryWarning((res) => {
        console.warn('[小程序性能] 内存警告');
        this.handleMemoryWarning();
        this.triggerOptimization('memoryWarning', res);
      });
    }

    // 定期检查内存使用（通过间接方式）
    this.checkMemoryUsage();
  }

  /**
   * 设置网络监控
   */
  setupNetworkMonitoring() {
    // 网络状态变化监听
    uni.onNetworkStatusChange((res) => {
      console.log(`[小程序性能] 网络状态变化: ${res.networkType}`);
      this.recordNetworkChange(res);
      
      if (!res.isConnected) {
        this.triggerOptimization('networkDisconnected', res);
      } else if (res.networkType === '2g' || res.networkType === '3g') {
        this.triggerOptimization('slowNetwork', res);
      }
    });
  }

  /**
   * 设置渲染性能监控
   */
  setupRenderMonitoring() {
    // 监控页面渲染性能
    this.startRenderTimeTracking();
  }

  /**
   * 记录视频加载时间
   */
  recordVideoLoadTime(videoId, startTime, endTime) {
    const loadTime = endTime - startTime;
    this.performanceData.videoLoadTime.push({
      videoId,
      loadTime,
      timestamp: Date.now()
    });

    if (loadTime > this.thresholds.videoLoadSlow) {
      console.warn(`[小程序性能] 视频加载缓慢: ${videoId}, 耗时: ${loadTime}ms`);
      this.triggerOptimization('slowVideoLoad', { videoId, loadTime });
    }

    // 保持数据数量限制
    if (this.performanceData.videoLoadTime.length > 50) {
      this.performanceData.videoLoadTime.shift();
    }
  }

  /**
   * 记录网络延迟
   */
  recordNetworkLatency(latency) {
    this.performanceData.networkLatency.push({
      latency,
      timestamp: Date.now()
    });

    if (latency > this.thresholds.networkSlow) {
      console.warn(`[小程序性能] 网络延迟高: ${latency}ms`);
      this.triggerOptimization('highLatency', { latency });
    }

    // 保持数据数量限制
    if (this.performanceData.networkLatency.length > 30) {
      this.performanceData.networkLatency.shift();
    }
  }

  /**
   * 网络延迟测试
   */
  async testNetworkLatency() {
    const startTime = Date.now();
    
    try {
      await new Promise((resolve, reject) => {
        uni.request({
          url: 'https://your-domain.com/ping', // 替换为您的测试接口
          method: 'GET',
          timeout: 5000,
          success: resolve,
          fail: reject
        });
      });
      
      const latency = Date.now() - startTime;
      this.recordNetworkLatency(latency);
      return latency;
    } catch (error) {
      console.warn('[小程序性能] 网络延迟测试失败:', error);
      return -1;
    }
  }

  /**
   * 检查内存使用情况
   */
  checkMemoryUsage() {
    // 小程序无法直接获取内存使用，通过间接方式估算
    const estimatedUsage = this.estimateMemoryUsage();
    
    this.performanceData.memoryUsage.push({
      estimated: estimatedUsage,
      timestamp: Date.now()
    });

    // 保持数据数量限制
    if (this.performanceData.memoryUsage.length > 20) {
      this.performanceData.memoryUsage.shift();
    }
  }

  /**
   * 估算内存使用
   */
  estimateMemoryUsage() {
    // 通过运行时间、创建对象数量等估算内存使用
    const runTime = Date.now() - this.performanceData.startTime;
    const dataCount = Object.values(this.performanceData).reduce((sum, arr) => 
      sum + (Array.isArray(arr) ? arr.length : 0), 0
    );
    
    // 简单的启发式估算（实际项目中可以根据具体情况调整）
    const estimatedMB = Math.min((runTime / 60000) * 2 + (dataCount * 0.1), 50);
    
    return {
      estimatedMB: estimatedMB.toFixed(2),
      runTimeMinutes: (runTime / 60000).toFixed(1),
      dataPoints: dataCount
    };
  }

  /**
   * 渲染时间追踪
   */
  startRenderTimeTracking() {
    const renderStart = Date.now();
    
    // 使用nextTick检测渲染完成
    this.$nextTick && this.$nextTick(() => {
      const renderTime = Date.now() - renderStart;
      this.recordRenderTime(renderTime);
    });
  }

  /**
   * 记录渲染时间
   */
  recordRenderTime(renderTime) {
    this.performanceData.renderTime.push({
      renderTime,
      timestamp: Date.now()
    });

    if (renderTime > this.thresholds.renderSlow) {
      console.warn(`[小程序性能] 渲染缓慢: ${renderTime}ms`);
      this.triggerOptimization('slowRender', { renderTime });
    }

    // 保持数据数量限制
    if (this.performanceData.renderTime.length > 30) {
      this.performanceData.renderTime.shift();
    }
  }

  /**
   * 记录网络状态变化
   */
  recordNetworkChange(networkInfo) {
    console.log(`[小程序性能] 网络变化: ${networkInfo.networkType}, 连接状态: ${networkInfo.isConnected}`);
    
    // 记录网络变化历史
    if (!this.performanceData.networkHistory) {
      this.performanceData.networkHistory = [];
    }
    
    this.performanceData.networkHistory.push({
      ...networkInfo,
      timestamp: Date.now()
    });

    // 保持数据数量限制
    if (this.performanceData.networkHistory.length > 20) {
      this.performanceData.networkHistory.shift();
    }
  }

  /**
   * 定期性能检查
   */
  performanceCheck() {
    if (!this.monitoringEnabled) return;

    console.log('[小程序性能] 执行定期性能检查');

    // 检查平均性能指标
    const stats = this.getPerformanceStats();
    
    if (stats.avgVideoLoadTime > this.thresholds.videoLoadSlow) {
      this.triggerOptimization('consistentSlowVideoLoad', stats);
    }
    
    if (stats.avgNetworkLatency > this.thresholds.networkSlow) {
      this.triggerOptimization('consistentHighLatency', stats);
    }
    
    if (stats.avgRenderTime > this.thresholds.renderSlow) {
      this.triggerOptimization('consistentSlowRender', stats);
    }

    // 测试网络延迟
    this.testNetworkLatency();
  }

  /**
   * 处理内存警告
   */
  handleMemoryWarning() {
    console.warn('[小程序性能] 处理内存警告，执行清理');
    
    // 清理性能数据
    this.clearOldPerformanceData();
    
    // 触发内存优化
    this.triggerOptimization('memoryCleanup', {
      reason: 'memoryWarning',
      timestamp: Date.now()
    });
  }

  /**
   * 清理旧的性能数据
   */
  clearOldPerformanceData() {
    const maxDataPoints = 10;
    
    Object.keys(this.performanceData).forEach(key => {
      if (Array.isArray(this.performanceData[key])) {
        this.performanceData[key] = this.performanceData[key].slice(-maxDataPoints);
      }
    });
    
    console.log('[小程序性能] 性能数据已清理');
  }

  /**
   * 注册优化回调
   */
  onOptimizationNeeded(type, callback) {
    if (!this.optimizationCallbacks.has(type)) {
      this.optimizationCallbacks.set(type, []);
    }
    this.optimizationCallbacks.get(type).push(callback);
  }

  /**
   * 触发优化
   */
  triggerOptimization(type, data) {
    console.log(`[小程序性能] 触发优化: ${type}`, data);
    
    const callbacks = this.optimizationCallbacks.get(type);
    if (callbacks) {
      callbacks.forEach(callback => {
        try {
          callback(data);
        } catch (error) {
          console.error(`[小程序性能] 优化回调执行失败: ${type}`, error);
        }
      });
    }
  }

  /**
   * 获取性能统计
   */
  getPerformanceStats() {
    const stats = {
      totalRunTime: Date.now() - this.performanceData.startTime,
      avgVideoLoadTime: this.calculateAverage(this.performanceData.videoLoadTime, 'loadTime'),
      avgNetworkLatency: this.calculateAverage(this.performanceData.networkLatency, 'latency'),
      avgRenderTime: this.calculateAverage(this.performanceData.renderTime, 'renderTime'),
      dataPoints: {
        videoLoads: this.performanceData.videoLoadTime.length,
        networkTests: this.performanceData.networkLatency.length,
        renders: this.performanceData.renderTime.length
      }
    };

    return stats;
  }

  /**
   * 计算平均值
   */
  calculateAverage(dataArray, key) {
    if (dataArray.length === 0) return 0;
    
    const sum = dataArray.reduce((total, item) => total + (item[key] || 0), 0);
    return Math.round(sum / dataArray.length);
  }

  /**
   * 获取性能报告
   */
  getPerformanceReport() {
    const stats = this.getPerformanceStats();
    const estimatedMemory = this.estimateMemoryUsage();
    
    return {
      timestamp: Date.now(),
      runtime: {
        totalMinutes: (stats.totalRunTime / 60000).toFixed(1),
        monitoringEnabled: this.monitoringEnabled
      },
      performance: {
        avgVideoLoadTime: stats.avgVideoLoadTime + 'ms',
        avgNetworkLatency: stats.avgNetworkLatency + 'ms', 
        avgRenderTime: stats.avgRenderTime + 'ms'
      },
      memory: estimatedMemory,
      dataPoints: stats.dataPoints,
      recommendations: this.getOptimizationRecommendations(stats)
    };
  }

  /**
   * 获取优化建议
   */
  getOptimizationRecommendations(stats) {
    const recommendations = [];
    
    if (stats.avgVideoLoadTime > this.thresholds.videoLoadSlow) {
      recommendations.push('视频加载缓慢，建议降低视频质量或减少预加载数量');
    }
    
    if (stats.avgNetworkLatency > this.thresholds.networkSlow) {
      recommendations.push('网络延迟较高，建议优化网络请求或启用离线模式');
    }
    
    if (stats.avgRenderTime > this.thresholds.renderSlow) {
      recommendations.push('页面渲染较慢，建议优化DOM结构或减少同时显示的元素');
    }
    
    if (stats.dataPoints.videoLoads > 20) {
      recommendations.push('视频加载次数较多，建议优化缓存策略');
    }
    
    if (recommendations.length === 0) {
      recommendations.push('性能表现良好，继续保持');
    }
    
    return recommendations;
  }

  /**
   * 性能优化建议
   */
  static getGeneralOptimizationTips() {
    return [
      '视频优化：使用适当的分辨率和码率',
      '缓存优化：合理设置缓存大小和过期时间',
      '网络优化：使用CDN和域名预解析',
      '内存优化：及时清理不用的资源',
      '渲染优化：避免复杂的CSS动画和过多的DOM操作',
      '用户体验：提供加载状态反馈和错误处理',
      '小程序特有：遵循小程序的性能规范和限制'
    ];
  }

  /**
   * 重置性能数据
   */
  resetPerformanceData() {
    this.performanceData = {
      memoryUsage: [],
      networkLatency: [],
      renderTime: [],
      videoLoadTime: [],
      startTime: Date.now()
    };
    
    console.log('[小程序性能] 性能数据已重置');
  }

  /**
   * 导出性能数据
   */
  exportPerformanceData() {
    return {
      ...this.performanceData,
      report: this.getPerformanceReport(),
      thresholds: this.thresholds
    };
  }
}

export default MiniProgramPerformance;